import 'package:logger/logger.dart';

import '../dao/ImConfigDao.dart';
import '../pojo/ImPojo.dart';
import '../socket/dto/business/PullData2.dart';
import 'BaseService.dart';

class ImConfigService extends BaseService {
  final _logger = Logger(printer: PrettyPrinter(),);

  Future<List<ImConfig>> saveOrUpdates(String userId, List<ConfigItem> configItemList) async {
    if (configItemList.isEmpty) return Future.value([]);

    final configDao = ImConfigDao();
    var imConfigs = configItemList.map((configItem)=>_toConfig(userId, configItem)).toList();

    List<String> codeList = configItemList.map((e) => e.name).toList();
    List<ImConfig> dbConfigs = await configDao.getByNames(codeList);

    Set<String> dbCodeSet = dbConfigs.map((g) => g.name).toSet();
    List<ImConfig> insertConfigs = imConfigs.where((g) => !dbCodeSet.contains(g.name)).toList();
    List<ImConfig> updateConfigs = imConfigs.where((g) => dbCodeSet.contains(g.name)).toList();

    await configDao.batchInserts(insertConfigs);
    await configDao.batchUpdates(updateConfigs);

    return imConfigs;
  }

  ImConfig _toConfig(String userId, ConfigItem configItem) {
    ImConfig config = ImConfig(name: configItem.name,
      currentUserId: userId,
      content: configItem.content,
      status: ImConfigStatus.ofValue(configItem.status.value),
    );
    return config;
  }
}